import datetime
from dateutil.relativedelta import relativedelta
import calendar

# 根据当前小时获取过去的小时
def getHour(hour):
    hours = []
    for h in range(0,int(hour)+1):
        if len(str(h)) == 1:
            h = '0'+str(h)
        else:
            h = str(h)
        hours.append(h)
    return hours
# 根据时间获取过去的日期
def getDay(num,endtime):
    days = []
    now = datetime.datetime.strptime(endtime,'%Y-%m-%d %H:%M:%S')
    for i in range(num):
        date = now + datetime.timedelta(days=-i)
        days.append(date.strftime('%m-%d'))
    return days
# 根据当前时间获取过去的月份
def getMonths(endtime):
    months = []
    now = datetime.datetime.strptime(endtime,'%Y-%m-%d %H:%M:%S')
    for i in range(12):
        date = now+relativedelta(months=-i)
        months.append(date.strftime('%Y-%m'))
    return months
# 获取开始和结束之间的日期
def getDays(startTime,endtime):
    y1,m1,d1 = startTime.split('-')

    y2,m2,d2 = endtime.split('-')

    num = (datetime.datetime(int(y2),int(m2),int(d2)) - datetime.datetime(int(y1),int(m1),int(d1))).days

    dates = []
    now = datetime.datetime.strptime(endtime,'%Y-%m-%d')
    for i in range(num):
        date = now+relativedelta(days=-i)
        dates.append(date.strftime('%Y-%m-%d'))
    dates.append(startTime)
    return dates
# 获取某年某月的第一天和最后一天
def getFirst_and_last_days(year,month):
    weekDay,monthCountDay = calendar.monthrange(int(year),int(month))
    first = str(datetime.date(int(year),int(month),day=1))
    last = str(datetime.date(int(year),int(month),day=monthCountDay))
    return first,last
